package database

import (
	"errors"
	"gorm.io/gorm"
	"time"
)

// GetSessionByID 根据session ID获取Session信息
func GetSessionByID(id string) (*Session, error) {
	var session Session
	result := db.Where("id = ?", id).First(&session)
	if result.Error != nil {
		return nil, result.Error
	}
	return &session, nil
}

// CreateSession 创建一个新的Session
func CreateSession(session *Session) error {
	result := db.Create(session)
	return result.Error
}

// UpdateSession 更新Session信息
func UpdateSession(session *Session) error {
	result := db.Save(session)
	return result.Error
}

// DeleteSessionByID 根据session ID删除Session记录
func DeleteSessionByID(id string) error {
	result := db.Delete(&Session{}, "id = ?", id)
	return result.Error
}

// GetSessionsByUserID 根据用户ID获取其所有的Session记录
func GetSessionsByUserID(userID int64) ([]Session, error) {
	var sessions []Session
	result := db.Where("user_id = ?", userID).Find(&sessions)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return nil, result.Error
	}
	return sessions, result.Error
}

// ExpireSessionsByTime 清除过期的Session记录
func ExpireSessionsByTime(expirationTime time.Time) error {
	result := db.Delete(&Session{}, "expiration_time < ?", expirationTime)
	return result.Error
}
